'use strict'

let product = [
    {
        id: 1,
        name: '衬衫',
        price: 58,
        stock: 20,
        supplier: '以纯'
    },
    {
        id: 2,
        name: '牛仔裤',
        price: 99,
        stock: 20,
        supplier: '李宁',
    },
    {
        id: 3,
        name: '皮带',
        price: 39,
        stock: 15,
        supplier: '七匹狼'
    }
]

// 首页
let fn_product = (ctx, next) => {
    let keyword = ctx.request.query.keyword
    if (keyword) {
        ctx.body = data.filter(item => {
            return item.id == keyword || item.name == keyword || item.price == keyword ||
                item.stock == keyword || item.supplier == keyword
        })
    } else {
        ctx.body = product
    }
}

// 新增
let fn_post = (ctx, next) => {
    let obj = ctx.request.body
    obj.id = product[product.length - 1].id + 1
    product.push(obj)
    ctx.body = product
}

// 编辑
let fn_put = (ctx, next) => {
    let obj = ctx.request.body
    console.log(obj);
    product.forEach(item => {
        if (item.id == obj.id) {
            item.name = obj.name
            item.price = obj.price
            item.stock = obj.stock
            item.supplier = obj.supplier
        }
    })
    console.log(product);
    ctx.body = product
}

// 删除
let fn_delete = (ctx, next) => {
    let id = ctx.request.params.id
    let newArr = product.filter(item => {
        return id != item.id
    })
    product = newArr
    ctx.body = product
}

module.exports = {
    'get /product': fn_product,
    'delete /product/:id': fn_delete,
    'post /product': fn_post,
    'put /product': fn_put
}